// pages/home/home.js
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    //信息控制框
    isFirstLongin: true,
    // 菜单高度
    menuHeight: 0,
    menuList: [{
        id: 1,
        iconName: "yijianfankui",
        menuName: "反馈历史",
        goPage: "stop"
      },
      {
        id: 1,
        iconName: "guanyuwomen",
        menuName: "关于我们",
        goPage: "/subIndex/pages_first/about_us/about_us"
      },
    ],
    userInfo: {},
    // 身份
    identity_name: null,
    identityList: null,
    // 处理后的身份列表
    handleIdentityList: [],
    loading: false, //处理身份加载的loading
    showIdentity: false, //切换身份
  },
  // 登录
  tologin() {
    wx.showLoading({
      title: '登录中~',
      mask: true
    });
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.globalData.url + '/login',
          method: 'POST',
          data: {
            code: res.code
          },
          success: (res) => {
            wx.hideLoading()
            console.log(res);
            //  res.data.status==fasle 是首次登录 需要弹出信息框让填写信息
            app.globalData.userInfo.open_id = res.data.unique_identification
            if (res.data.status !== 200) {
              wx.showToast({
                title: res.data.msg,
              })
              return
            }
            // isFirstLogin 为false表示数据库没有用户信息首次登录系统 反之 是老师的话要核验 登录填完信息了但是没有核验
            this.setData({
              isFirstLongin: res.data.isFirstLongin,
            });
            if (res.data.data == null) {
              return;
            }
            if (res.data.isFirstLongin && res.data.data.confirm_identity == 0) {
              // 已经提交过审核
              wx.showLoading({
                title: res.data.msg,
              })
              setTimeout(function () {
                wx.hideLoading()
                wx.navigateTo({
                  url: '/subpacks/pages_first/examine/detailresult/detail',
                })
              }, 2000)
              return;
            };
            // 正常登录
            let {
              session_key,
              confirm_identity,
              createdAt,
              updatedAt,
              ...userInfo
            } = res.data.data
            app.globalData.userInfo = userInfo
            wx.setStorageSync('token', res.data.data.token);
            wx.setStorageSync('userInfo', res.data.data);
            console.log(app.globalData.userInfo);
            this.setData({
              isLogin: true,
              userInfo: userInfo
            })
            this.get_identity_ID()
            this.getIdentityList()
          }
        })
      }
    });
  },
  // 页面跳转 退出登录 url==none
  to_page(e) {
    if (e.currentTarget.dataset.url == "none") {
      // 退出登录 清除本地缓存
      try {
        wx.clearStorageSync()
        app.globalData.userInfo = {
          nickname: null,
          avatar_url: "https://ruan-cso-1318331856.cos.ap-guangzhou.myqcloud.com/%E5%A4%B4%E5%83%8F.png",
          face_url: null,
          username: null,
          phone: null,
          adress_ID: null,
          address_name: null,
          school_ID: null,
          school_name: null,
          college_ID: null,
          college_name: null,
          sex: 0,
          student_id: null,
          teacher_id: null,
          class_ID: null,
          class_name: null,
          identity_ID: null,
          position_name: null,
          position_ID: null,
          token: null,
          open_id: null
        }
        this.setData({
          userInfo: app.globalData.userInfo,
          isLogin: false
        })

      } catch (error) {
        wx.showModal({
          title: '错误',
          content: "退出失败请重试" + error,
          showCancel: false,
          complete: (res) => {}
        })
      }
      wx.showToast({
        title: '退出成功',
      })
      return;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  // 关闭昵称头像选择
  onClose() {
    this.setData({
      isFirstLongin: true
    })
  },
  // 用户选中图片
  async bindchooseavatar(e) {
    wx.showToast({
      title: '上传成功~',
    })
    console.log(e.detail.avatarUrl, e);
    // 拿到图片信息 转base64 上传os获取在线图片地址
    let imgName = e.detail.avatarUrl;
    let imgType = null;
    // 如果需要获取图片类型的话
    wx.getImageInfo({
      src: imgName,
      success(res) {
        console.log(res);
        imgType = res.type
      }
    });
    let imgBase64 = null;
    const fs = wx.getFileSystemManager()
    // 同步接口
    try {
      const res = fs.readFileSync(e.detail.avatarUrl, 'base64', 0)
      console.log("图片的base64：", res)
      imgBase64 = res
    } catch (e) {
      wx.showToast({
        title: e,
      })
    }
    // 删除 "http://"  
    imgName = imgName.replace("http://", "");
    // // 删除文件的扩展名，包括 "."  
    // imgName = imgName.replace(/\.[^.]+$/, "");
    let json = await getApp().$axios("/uploadImg", "POST", {
      base64: `data:image/${imgType};base64,` + imgBase64,
      imgName
    })
    console.log(json, "图片在线地址");
    app.globalData.userInfo.avatar_url = 'https://' + json.imgUrl
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },
  // 用户填好昵称
  bindnicknamereview(e) {
    console.log(e);
    // 在真机上才能生效。开发者工具有bug
    app.globalData.userInfo.nickname = e.detail.value
    this.setData({
      userInfo: app.globalData.userInfo
    });
    console.log(this.data.userInfo);
  },
  // 校验表单并进行下一步
  check_login() {
    if (this.data.userInfo.nickname == null) {
      wx.showToast({
        title: "请输入用户昵称",
        icon: 'error'
      })
      return;
    };
    this.setData({
      isFirstLongin: true
    })
    wx.navigateTo({
      url: '/pages/identitySelection/identitySelection',
    })
  },
  // 计算职位
  get_identity_ID() {
    let identity_ID = ["", "学生", "老师", "超级管理员"];
    this.setData({
      identity_name: identity_ID[this.data.userInfo.identity_ID]
    })
  },
  // 获取身份列表
  async getIdentityList() {
    let uid = this.data.userInfo.id;
    try {
      let json = await getApp().$axios("/getIdentityList?id=" + uid, "GET")
      wx.hideLoading()
      console.log(json);
      if (json.status !== 200) {
        wx.showToast({
          title: json.msg,
          icon: 'error'
        })
        return
      }
      this.setData({
        identityList: json.data
      })
    } catch (error) {
      console.log(error);
      wx.hideLoading()
      if (error.status && error.status == 500) {
        wx.showModal({
          title: '提示',
          content: 'token信息已过期，重新登录',
          showCancel: false,
          complete: (res) => {
            wx.clearStorageSync()
          }
        })
        return
      }
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 打开切换身份popup
  onShowIdentity() {
    this.setData({
      showIdentity: !this.data.showIdentity,
      loading: true,
      handleIdentityList: []
    })
    this.data.identityList.forEach(i => {
      this.data.handleIdentityList.push(i.identity_num.iden_name)
    });
    this.setData({
      handleIdentityList: this.data.handleIdentityList,
      loading: false
    })
  },
  // 确认切换身份
  async onConfirmIdentity(e) {
    console.log(e.detail);
    let {
      index,
      value
    } = e.detail;
    const iID = this.data.identityList[index].identity_id
    const uid = this.data.userInfo.id
    try {
      const json = await getApp().$axios("/changeIdentity", "POST", {
        uid,
        identity_ID: iID
      })
      console.log(json);
      if (json.status !== 200) {
        wx.showToast({
          title: json.msg,
          icon: 'error'
        })
        return
      }
      app.globalData.userInfo = json.data
      wx.setStorageSync('userInfo', json.data)
      this.setData({
        userInfo: json.data
      })
      this.get_identity_ID()
      this.onShowIdentity()
    } catch (error) {
      wx.showToast({
        title: '切换身份接口出问题',
        icon: 'error'
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(app.globalData.systemInfo);
    const token = wx.getStorageSync("token")
    if (!token) {
      this.setData({
        isLogin: false
      });
    } else {
      this.setData({
        isLogin: true
      });
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.showLoading({
      title: '加载中~',
    })
    // 计算margin的值
    let avatarMarginpx = app.globalData.systemInfo.windowWidth / 750 * 50;
    let spaceMarginpx = app.globalData.systemInfo.windowWidth / 750 * 100;
    // 菜单高度px
    let menuHeightPx = 0
    // 菜单高度转rpx
    let menuHeightRpx = 0
    // 获取头像盒子高度
    let avatarHeight = 0
    wx.createSelectorQuery().select('.avatar').boundingClientRect((rect) => {
      console.log('元素的高度：', rect.height);
      avatarHeight = rect.height
      console.log('元素的信息：', rect);
    }).exec();
    // 获取分隔盒子的高度
    let spaceHeight = 0
    wx.createSelectorQuery().select('.space').boundingClientRect((rect) => {
      console.log('元素的高度：', rect.height);
      spaceHeight = rect.height
      console.log('元素的信息：', rect);
      menuHeightPx = app.globalData.systemInfo.windowHeight - (avatarHeight + spaceHeight + avatarMarginpx + spaceMarginpx) - app.globalData.systemInfo.statusBarHeight - app.globalData.systemInfo.CustomBarHeight;
      // 结果转rpx
      menuHeightRpx = (750 / app.globalData.systemInfo.windowWidth) * menuHeightPx;

      console.log(avatarHeight, spaceHeight, avatarMarginpx, spaceMarginpx, menuHeightPx, avatarHeight + spaceHeight + avatarMarginpx + spaceMarginpx);
      this.setData({
        menuHeight: menuHeightRpx
      })
    }).exec();
    this.setData({
      userInfo: app.globalData.userInfo
    })
    this.get_identity_ID()
    this.getIdentityList()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})